package sunbao.ido.support;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;
import sunbao.ido.factory.IDoFactoryBean;
import sunbao.ido.stereotype.IDoScan;

/**
 * \* User: MeiZhongHao
 * \* Date: 2018-10-23
 * \* Time: 11:51
 * \* Description: 通过扫描器，初始化对应IDo Bean
 * \  这个接口的实现类的作用是当这个接口的实现类被@Import接口引入某个被标记了@Configuration的注册类时，
 *    可以得到这个类的所有注解，然后做一些动态注册Bean的事儿。
 */
public class IDoScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    private ResourceLoader resourceLoader;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(IDoScan.class.getName()));
        ClassPathIDoScanner scanner = new ClassPathIDoScanner(beanDefinitionRegistry);
        if (this.resourceLoader != null) {
            scanner.setResourceLoader(this.resourceLoader);
        }
        String[] basePackage = annoAttrs.getStringArray("basePackage");
        if (StringUtils.isEmpty(basePackage)) {
            return;
        }
        Class<? extends IDoFactoryBean> iDofactoryBeanClass = annoAttrs.getClass("factoryBean");
        if (IDoFactoryBean.class.equals(iDofactoryBeanClass)) {
            scanner.setiDoFactoryBean(BeanUtils.instantiateClass(iDofactoryBeanClass));
        }
        scanner.registerTypeFilter();
        scanner.doScan(basePackage);
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}